#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_XPM_Image.H>
#include <FL/Enumerations.H>
#include <FL/fl_draw.H>
//#include "final_designer_1.xpm"
#include <SDL/SDL.h>
#include <assert.h>
#include <unistd.h>

int quit = 0;

struct CLIArgs {
  int argc;
  char **argv;
};
 

class MyWin : public Fl_Window {
  Fl_XPM_Image myimg; 

public:
  MyWin(int w, int h) : Fl_Window(w, h), myimg("final_designer_1.xpm") {
  }

protected:
  virtual void draw() {
    fl_color(FL_CYAN);
    fl_rectf(0,0,40,512);
    myimg.draw(2, 3);
  };
};

int mythread(void *ptr) {
  Uint32 col;
  SDL_Event event;
  SDL_Surface *scr = (SDL_Surface *)ptr;
  Uint8 counter = 0;

  while(!quit) {
    col = SDL_MapRGB(scr->format, counter, counter, counter);
    ++counter;
    SDL_FillRect(scr, NULL, col);
    SDL_Flip(scr);
    SDL_Delay(44);
    while(SDL_PollEvent(&event) == 1) {
      switch(event.type) {
        case SDL_QUIT:
          quit = 2;
          break;
        case SDL_MOUSEBUTTONDOWN:
        case SDL_MOUSEBUTTONUP:
          printf("button=%d state=%d x=$%04hX y=$%04hX\n", event.button.button, event.button.state, event.button.x, event.button.y);
          break;
        case SDL_KEYDOWN:
        case SDL_KEYUP:
          printf("state=%d sym=$%04X\n", event.key.state, event.key.keysym.sym);
          break;
        default:
          printf("event.type = $%x\n", (unsigned int)event.type);
        }
    }
  }
  return -42;
}

int fltkthread(void *null) {
  int ret;
  CLIArgs *args = static_cast<CLIArgs *>(null);

  MyWin *window = new MyWin(40,528);
  // Fl_Box *box = new Fl_Box(20,40,300,100,"Hello, World!");
  // box->box(FL_UP_BOX);
  // box->labelfont(FL_BOLD+FL_ITALIC);
  // box->labelsize(36);
  // box->labeltype(FL_SHADOW_LABEL);
  window->end();
  window->show(args->argc, args->argv);
  ret = Fl::run();
  printf("fltkthread ret = %d\n", ret);
  quit = 3;
  return quit;
}

int main(int argc, char **argv) {
  int ret, tret;
  SDL_Surface *scr;
  SDL_Thread *thd, *flthd;
  CLIArgs args = { argc, argv };

  assert(SDL_Init(SDL_INIT_VIDEO) == 0);
  scr = SDL_SetVideoMode(800, 480, 32, SDL_HWSURFACE|SDL_ANYFORMAT|SDL_DOUBLEBUF);
  assert(scr);
  thd = SDL_CreateThread(mythread, scr);
  assert(thd);
  flthd = SDL_CreateThread(fltkthread, &args);
  assert(flthd);
  SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); //Ignore all mouse movements...

  printf("SC_PAGE_SIZE = $%08lx\n", sysconf(_SC_PAGE_SIZE));
  for(ret = 0; !quit && ret < 1000; ++ret) {
    printf("counter: $%x\n", ret);
    SDL_Delay(2000);
  }
  SDL_WaitThread(thd, &tret);
  printf("tret = %d\n", tret);
  SDL_KillThread(flthd);
  SDL_Quit();
  return ret;
}

// g++ -Wall -O1 display_64font.sdl_fltk.cc -lfltk -lSDL
// g++ display_64font.sdl_fltk.cc -lSDL -lfltk -lXext -lX11 -ldl -lpthread
